from socket import *
from threading import Thread


# HOST = "0.0.0.0"
# PORT = 8888
# ADDR = (HOST, PORT)
#
#
# class Web:
#     def __init__(self):
#         self.addr = ADDR
#         self.sock = socket()
#
#     def handle(self, conn, addr):
#         while True:
#             data = conn.recv(1024)
#             if not data:
#                 break
#             print("")
#             conn.send(b"OK")
#         conn.close()
#
#     def main(self):
#         self.sock.bind(self.addr)
#         self.sock.listen()
#         print("Listen... ...")
#         while True:
#             conn, addr = self.sock.accept()
#             print("Connect from :", addr)
#             p = Thread(target=self.handle, args=(conn, addr))
#             p.start()


class Handle(Thread):
    def __init__(self, conn, addr):
        self.conn = conn
        self.address = addr
        super().__init__()

    def run(self):
        while True:
            data = self.conn.recv(1024)
            if not data:
                break
            print(data.decode())
            self.conn.send(b"OK")
        self.conn.close()


class ThreadServer:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self._create_socket()

    def _create_socket(self):
        sock = socket()
        sock.bind(self.address)
        return sock

    # 启动服务
    def serve_forever(self):
        self.sock.listen()
        print("Listen the port :", self.port)
        while True:
            conn, addr = self.sock.accept()
            print("Connect from :", addr)
            t = Handle(conn, addr)
            t.start()


if __name__ == '__main__':
    server = ThreadServer(host="0.0.0.0", port=8888)
    server.serve_forever()
